<?php

namespace App\Services\MakeProductThumbnail;

use App\Models\Divination;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class MakeProductThumbnail
{
	/**
	 * @var User
	 */
	protected $user;
	
	/**
	 * @var Product
	 */
	protected $divination;
	
	
	public function __construct(Divination $divination)
	{
		$this->divination = $divination;
	}

	protected function getPosterName($cover)
	{
		return basename($cover);
	}
	
	protected function getRemotePosterDir($cover)
	{

		$dirname = dirname($cover);
		$dirname = str_replace('https://littleshop.oss-cn-beijing.aliyuncs.com/','',$dirname);
		return $dirname;
	}
	
	protected function getRemotePosterSavePath($cover)
	{
		return $this->getRemotePosterDir($cover) . '/' . $this->getPosterName($cover);
	}
	
	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('app/mini-product-thumbnail');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.jpg";
	}
	
	public function make()
	{
		$divination = $this->divination;
		
		$posterName = $this->getPosterName($divination->image);

		if(!empty($divination->image)){
			$cover = Image::make(public_path("app/".$divination->image))->resize(1242, 2203);
		
			Image::canvas(1242, 2203, '#FFFFFF')
				->insert($cover, 'top', 0, 0)
				->save($this->getLocalPosterSavePath($posterName));
		}
		
		// remove local poster.
		File::delete(public_path("app/".$divination->image));
		
		$divination->update(['image'=>"/mini-product-thumbnail/".$posterName.".jpg"]);
	}
}
